﻿using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Microsoft.Practices.Prism.Mvvm.Interfaces;

namespace Demo01.ViewModels
{
    public interface IDetailPageViewModel
    {
        Models.Item Item { get; set; }
        DelegateCommand GoBackCommand { get; }
    }

    public class DetailPageViewModel : ViewModel, IDetailPageViewModel
    {
        INavigationService _navigationService;
        Repositories.IItemRepository _itemRepository;
        public DetailPageViewModel(INavigationService navigationService,
            Repositories.IItemRepository itemRepository)
        {
            _navigationService = navigationService;
            _itemRepository = itemRepository;
        }

        public override void OnNavigatedTo(object navigationParameter, Windows.UI.Xaml.Navigation.NavigationMode navigationMode, Dictionary<string, object> viewModelState)
        {
            base.OnNavigatedTo(navigationParameter, navigationMode, viewModelState);
            if (!viewModelState.Any())
            {
                this.Item = _itemRepository.AllItems()
                    .First(x => x.Text == navigationParameter.ToString());
            }
        }

        Models.Item _Item = default(Models.Item);
        [RestorableState]
        public Models.Item Item { get { return _Item; } set { SetProperty(ref _Item, value); } }

        DelegateCommand _GoBackCommand = null;
        public DelegateCommand GoBackCommand
        {
            get
            {
                if (_GoBackCommand != null)
                    return _GoBackCommand;
                _GoBackCommand = new DelegateCommand
                (
                    () => { _navigationService.GoBack(); },
                    () => { return true; }
                );
                this.PropertyChanged += (s, e) => _GoBackCommand.RaiseCanExecuteChanged();
                return _GoBackCommand;
            }
        }
    }
}
